import { getKnowLedgeList, getKnowLedgeDetail } from '@/services';
import { IKnowLedgeItem, IKnowLedgeDetailList } from '@/types';
import { Effect, Reducer } from 'umi';

export interface KnowLedgeModelState {
    knowledgeList: IKnowLedgeItem[]
    knowledgeLength: number,
    knowledgeDetailList: IKnowLedgeDetailList
}

export interface KnowLedgeModelType {
    namespace: 'knowLedge';

    state: KnowLedgeModelState;
    effects: {
        getKnowLedgeList: Effect;
        getKnowLedgeDetail: Effect;
    };
    reducers: {
        save: Reducer<KnowLedgeModelState>;
    };
}

const KnowLedgeModel: KnowLedgeModelType = {
    //等价于vuex的namespace   相当于redux的子reduce
    namespace: 'knowLedge',

    //定义的状态
    state: {
        knowledgeList: [],
        knowledgeLength: 0,
        knowledgeDetailList: {} as IKnowLedgeDetailList
    },

    //副作用 对应的异步操作，常指网络请求
    effects: {
        *getKnowLedgeList({ payload }, { call, put }) {
            //call改变this指向
            const result = yield call(getKnowLedgeList);
            if (result.data) {
                yield put({
                    type: "save",
                    payload: {
                        knowledgeList: result.data[0],
                        knowledgeLength: result.data[1]
                    }
                })
            }
        },
        *getKnowLedgeDetail({ payload }, { call, put }) {
            const result = yield call(getKnowLedgeDetail, payload);
            if (result.data) {
                yield put({
                    type: "save",
                    payload: {
                        knowledgeDetailList: result.data
                    }
                })
            }
        }
    },

    //同步操作
    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload,
            };
        },
    },
};

export default KnowLedgeModel;